<!--
 * @Author: Dorange.Wang
 * @Date: 2021-07-09 15:20:10
 * @LastEditors: your name
 * @LastEditTime: 2021-07-14 16:00:32
 * @Description: file content
-->
<template>
  <van-popup v-model="show" round position="bottom" :style="{ height: '80%' }">
    <div :class="b('toolbar')">
      <button type="button" :class="b('cancel')"
        @click="onCancel"
      >
        {{ options.cancelButtomText }}
      </button>
      <div :class="['van-ellipsis', b('title')]">{{ options.title }}</div>
      <button type="button" :class="b('confirm')" @click="onConfirm">
        {{ options.confirmButtomText }}
      </button>
    </div>

    <van-search
      v-if="options.allowSearch"
      v-model="keyword"
      placeholder="请输入"
      @search="onSearch"
    />

    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <van-checkbox-group v-model="checkedKeys">
          <van-cell
            clickable
            v-for="(item,index) in list"
            :key="item[options.rowValue]"
            :title="item[options.rowLabel]"
            @click="toggle(item, index)"
          >
            <template #right-icon>
              <van-checkbox
                :name="item[options.rowValue]"
                :shape="shape"
                ref="checkboxes"
              />
            </template>
          </van-cell>
        </van-checkbox-group>
      </van-list>
    </van-pull-refresh>
  </van-popup>
</template>

<script>
import Bem from "easy-bem";
import {cloneDeep} from 'lodash'

const DEFAULT_OPTIONS = {
  title: "",
  cancelButtomText: "取消",
  confirmButtomText: "确认",
  allowSearch: true,
  rowValue: "id",
  rowLabel: "label",
  listData: {},
  checkedKeys: [],
  checkedItems: [],
  multiple: false,
};
export default {
  name: "HanSelect",

  data() {
    return {
      b: Bem("han-select"),
      show: false,
      keyword: "",
      list: [],
      checkedKeys: [],
      pageNo: 1,
      loading: false,
      finished: false,
      error: false,
      refreshing: false,
      options: {
        ...DEFAULT_OPTIONS,
      },
    };
  },

  computed: {
    shape() {
      const { multiple } = this.options;
      return multiple ? "square" : "round";
    },
  },

  methods: {
    init(options = {}) {
      this.show = true;
      this.options = {
        ...DEFAULT_OPTIONS,
        ...options,
      };

      const { data, totalCount, pageNo } = options.listData;
      this.list = data;
      this.finished = this.list.length === totalCount;
      this.pageNo = pageNo;
      const checkedKeys = this.options.checkedKeys || [];
      this.checkedKeys = [...checkedKeys];
    },

    async loadData(pageNo = 1) {
      const { onSearch } = this.options;
      const { keyword } = this;
      if (!onSearch) {
        return;
      }
      this.loading = true;
      const listData = await onSearch({ keyword, pageNo });
      const { data, totalCount, pageNo: curPageNo } = listData;
      this.list = pageNo === 1 ? data : this.list.concat(data);
      this.finished = this.list.length === totalCount;
      this.pageNo = curPageNo;
      this.loading = false;
    },

    async onSearch() {
      this.loadData();
    },

    async onLoad() {
      this.loadData(this.pageNo + 1);
    },

    async onRefresh() {
      await this.loadData();
      this.refreshing = false;
    },

    toggle(item, index) {
      const value = item[rowValue];
      const oItem = cloneDeep(item)

      const { multiple, rowValue } = this.options;
      if (multiple) {
        // 多选
        this.$refs.checkboxes[index].toggle();
      } else {
        // 单选
        this.checkedKeys = [value];
        this.checkedItems = [oItem]
      }
    },

    onCancel(){
      this.show = false
    },

    onConfirm() {
      // console.log("onConfirm", this.options.checkedKeys);
    },
  },
};
</script>

<style lang="less" scoped>
@import "../../../node_modules/vant/lib/style/var";
.van-popup {
  display: flex;
  flex-direction: column;

  .van-pull-refresh {
    flex: 1;
    overflow: auto;
  }
}

.han-select {
  position: relative;
  background-color: @picker-background-color;
  user-select: none;

  &__toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    height: @picker-toolbar-height;
  }

  &__cancel,
  &__confirm {
    height: 100%;
    padding: @picker-action-padding;
    font-size: @picker-action-font-size;
    background-color: transparent;
    border: none;
    cursor: pointer;

    &:active {
      opacity: @active-opacity;
    }
  }

  &__confirm {
    color: @picker-confirm-action-color;
  }

  &__cancel {
    color: @picker-cancel-action-color;
  }

  &__title {
    max-width: 50%;
    font-weight: @font-weight-bold;
    font-size: @picker-title-font-size;
    line-height: @picker-title-line-height;
    text-align: center;
  }

  &__loading {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 3;
    display: flex;
    align-items: center;
    justify-content: center;
    color: @picker-loading-icon-color;
    background-color: @picker-loading-mask-color;
  }
}
</style>
